package com.yuezhu.versionup;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.yuezhu.R;
import com.yuezhu.constante.Intents;
import com.yuezhu.util.FileUtils;

import java.io.File;

public class DownService extends Service {
	private String taskId = "1";
	public static String appFileName = FileUtils.SDPATH+ "translation.apk";// 带后缀的文件名
	private NotificationManager notificationManager;
	private ProgressBar noti_progress_bar ;
	private Notification notification;
	private final static int NOTIFICATION_ID = 101;
	private int all = 0 ;
	private int mlen = 0;
	private String url;
	private int position = 0 ;
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		System.out.println("开始下载-----1111--");
		
		FileUtils.creatDirs();
		creatNotify();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		url = intent.getStringExtra(Intents.VERSION);
		down();
		System.out.println("开始下载--------------");
	}
	/**
	 * 显示和更新通知
	 */
	private void showOrUpdateNotification() {
		notificationManager.notify(NOTIFICATION_ID, notification);
	}
	public void creatNotify(){
		//获取NotificationManager
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		//构建通知
		notification = new Notification();
		//设置未下拉通知栏时弹出的提示
		//通知时在状态栏显示的内容，
		notification.tickerText = "下载程序";
		notification.icon = R.drawable.ic_launcher;

		//设置下拉通知栏显示的内容
		//构建一个远程View赋给Notification的contentView
		notification.contentView = new RemoteViews(getPackageName(), R.layout.layout_notification);
		//设置相应的View调用相应的方法
		//设置进度条，最大值为100,当前值为0，最后一个参数为true时显示条纹
		notification.contentView.setProgressBar(R.id.noti_progress_bar, 100, 0,false);
		notification.contentView.setTextViewText(R.id.noti_progress_textview, "0%");
	}

	// 启动下载
	public void down() {
		if (TaskQueue.getInst().size() == 0) {
			DownloadManager.getInstance(this).addDownTask(taskId,
					url,
					appFileName, mHandler);
		} else {
			DownloadManager.getInstance(this).continueTask(taskId,
					"http://common.okjiaoyu.cn/okpi_classroom-1.2.36.apk ",
					appFileName, mHandler);
		}
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			int length = msg.arg1;
			switch (msg.what) {
				case DownloadState.INIT:
					all = msg.arg2 ;
					//设置更新进度条
					notification.contentView.setProgressBar(R.id.noti_progress_bar,msg.arg2,msg.arg1, false);
					//设置更新进度
					notification.contentView.setTextViewText(R.id.noti_progress_textview, msg.arg1 + "%");
					showOrUpdateNotification();
					break;
				case DownloadState.DOWNLOADING:
					//设置更新进度条
					mlen = mlen + length ;

					//设置更新进度
					if (mlen>0) {
						float	pro_text = ( Float.parseFloat(mlen+"")/ Float.parseFloat(all+""))*100 ;
						int a = (int)pro_text;
						notification.contentView.setProgressBar(R.id.noti_progress_bar,all,mlen, false);
						notification.contentView.setTextViewText(R.id.noti_progress_textview,a + "%");
						if (position*2<=mlen) {
							position = mlen ;
							showOrUpdateNotification();
						}
						
						if (mlen == all) {
							Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_SHORT).show();
							notification.contentView.setTextViewText(R.id.noti_textview,"下载完成");
							showOrUpdateNotification();
							installApk(appFileName);
						}
					}

					break;
				case DownloadState.PAUSE:
					Log.d("暂停", "地址：【" + taskId + "】,进度:" + length);
					break;
				case DownloadState.ERROR:
					Log.d("下载任务异常", "地址：【" + taskId + "】,进度:" + length);
					break;
				default:
					break;
			}
		}
	};
	private void installApk(String filename) {
		File file = new File(filename);
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		String type = "application/vnd.android.package-archive";
		intent.setDataAndType(Uri.fromFile(file), type);
		startActivity(intent);

	}

}
